package ltd.dujiabao.springboot.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import ltd.dujiabao.springboot.service.HystrixService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author : DuJiabao
 * @Project : springcloud
 * @Time : 2021/5/22 19:34
 * @Desc :
 */
@Slf4j
@RestController
@Api("Consumer_Hystrix")
public class HystrixController {
  @Autowired
  HystrixService hystrixService;

  @GetMapping("/consumer/hystrix/ok/{id}")
  String runsWell(@PathVariable("id") Integer id) {
    String result = hystrixService.runsWell(id);
    log.info("result: " + result);
    return result;
  }

  @HystrixCommand(fallbackMethod = "runsTimeOutHandler",
          commandProperties = {@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1500")})
  @GetMapping("/consumer/hystrix/timeOut/{id}")
  public String runsTimeOut(@PathVariable("id") Integer id) {
    String result = hystrixService.runsTimeOut(id);
    log.info("result: " + result);
    return result;
  }

  public String runsTimeOutHandler(Integer id) {
    String result = "consumer 触发了服务降级，当前线程号：" + Thread.currentThread().getName();
    log.info(result);
    return result;
  }


  @GetMapping("/consumer/hystrix/exception/{id}")
  public String runsException(@PathVariable("id") Integer id) {
    String result = hystrixService.runsException(id);
    log.info("result: " + result);
    return result;
  }
}
